import express from 'express';

export function createTableRouter (db, tableName) {
  const router = express.Router();

  // 获取所有记录
  router.get('/', async (req, res, next) => {
    try {
      const { _page, _limit, _sort, _order, ...filters } = req.query;

      let query = db(tableName);

      // 应用过滤条件
      Object.entries(filters).forEach(([key, value]) => {
        query = query.where(key, value);
      });

      // 排序
      if (_sort) {
        query = query.orderBy(_sort, _order || 'asc');
      }

      // 分页
      if (_page && _limit) {
        const page = parseInt(_page);
        const limit = parseInt(_limit);
        const offset = (page - 1) * limit;

        const [count, data] = await Promise.all([
          db(tableName).count('* as count').first(),
          query.offset(offset).limit(limit)
        ]);

        res.setHeader('X-Total-Count', count.count);
        return res.json(data);
      }

      const data = await query.select();
      // 确保数据是数组
      const responseData = Array.isArray(data) ? data : [data].filter(Boolean);
      res.json(responseData);
    } catch (err) {
      next(err);
    }
  });

  // 获取单个记录
  router.get('/:id', async (req, res, next) => {
    try {
      const { id } = req.params;
      const data = await db(tableName).where('id', id).first();

      if (!data) {
        return res.status(404).json({ error: '记录不存在' });
      }

      res.json(data);
    } catch (err) {
      next(err);
    }
  });

  // 创建记录
  router.post('/', async (req, res, next) => {
    try {
      const [id] = await db(tableName).insert(req.body);
      const newRecord = await db(tableName).where('id', id).first();

      res.status(201).json(newRecord);
    } catch (err) {
      next(err);
    }
  });

  // 更新记录
  router.put('/:id', async (req, res, next) => {
    try {
      const { id } = req.params;
      await db(tableName).where('id', id).update(req.body);
      const updatedRecord = await db(tableName).where('id', id).first();

      if (!updatedRecord) {
        return res.status(404).json({ error: '记录不存在' });
      }

      res.json(updatedRecord);
    } catch (err) {
      next(err);
    }
  });

  // 删除记录
  router.delete('/:id', async (req, res, next) => {
    try {
      const { id } = req.params;
      const record = await db(tableName).where('id', id).first();

      if (!record) {
        return res.status(404).json({ error: '记录不存在' });
      }

      await db(tableName).where('id', id).delete();
      res.status(204).end();
    } catch (err) {
      next(err);
    }
  });

  return router;
}

export function createRouters (db, tables) {
  const router = express.Router();

  tables.forEach(tableName => {
    const tableRouter = createTableRouter(db, tableName);
    router.use(`/${tableName}`, tableRouter);
  });

  return router;
}